package com.soboot.security.interceptor;

import cn.hutool.core.util.StrUtil;
import com.soboot.base.constant.BaseConstant;
import com.soboot.base.util.ResponseUtil;
import com.soboot.response.Result;
import org.springframework.http.MediaType;
import org.springframework.util.Base64Utils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author:
 * @createTime: 2022年09月20日 12:57:20
 * @version: 1.0
 * @Description: 检验token有效性拦截器
 * @Copyright:
 */
public class ValidateTokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {

        //判断路由是否开放的

        // 从请求头中获取Token
        String token = request.getHeader(BaseConstant.Security.TOKENHEADER.getVal());
        String gatewayToken = new String(Base64Utils.encode(BaseConstant.Security.TOKENVALUE.getVal().getBytes()));
        // 校验Token的正确性
        if (StrUtil.equals(gatewayToken, token)) {
            return true;
        } else {
            ResponseUtil.writeResponse(MediaType.APPLICATION_JSON_VALUE,
                    HttpServletResponse.SC_FORBIDDEN, Result.fail("请通过网关获取资源"),response);
            return false;
        }
    }
}
